#!/usr/bin/python
# -*- coding: UTF-8 -*-
import time
import urllib.request
import urllib.parse
import json
import hashlib
import base64
from TTS import *
import tkinter as tk
#语言文本



def sa(TEXT):
    # 接口地址
    url = "http://ltpapi.xfyun.cn/v2/sa"
    # 开放平台应用ID
    x_appid = "69dfcbd1"
    # 开放平台应用接口秘钥
    api_key = "93b6f0a9dba79f51fee4b5604711a31b"
    body = urllib.parse.urlencode({'text': TEXT}).encode('utf-8')
    param = {"type": "dependent"}
    x_param = base64.b64encode(json.dumps(param).replace(' ', '').encode('utf-8'))
    x_time = str(int(time.time()))
    x_checksum = hashlib.md5(api_key.encode('utf-8') + str(x_time).encode('utf-8') + x_param).hexdigest()
    x_header = {'X-Appid': x_appid,
                'X-CurTime': x_time,
                'X-Param': x_param,
                'X-CheckSum': x_checksum}
    req = urllib.request.Request(url, body, x_header)
    result = urllib.request.urlopen(req)
    result = result.read()
    c=eval(result.decode('utf-8'))
    svm = c['data']['sentiment']
    if svm == 1:
        a = '看您心情不错，今日份的阳光很暖，适合跟喜欢的人一起逛街哦'
    elif svm == 0:
        a = '看您心情一般般,平平淡淡简单的生活才不会再有孤独'
    else:
        a = '看您很沮丧，失落只是一瞬间，开心才是真理哦'
    return a

def on_open(ws):
    def run(*args):
        d = {"common": wsParam.CommonArgs,
             "business": wsParam.BusinessArgs,
             "data": wsParam.Data,
             }
        d = json.dumps(d)

        ws.send(d)
        if os.path.exists('./demo.mp3'):
            os.remove('./demo.mp3')

    thread.start_new_thread(run, ())

class win1():
    def __init__(self):
        pass
    def run(self):
        self.windows=tk.Tk()
        self.windows.title("情感分析")
        self.windows.geometry("380x200")
        self.label=tk.Label


        self.windows.mainloop()






if __name__ == '__main__':

    c='今天很难过，考试没考好'
    svc=sa(c)
    wsParam = Ws_Param(APPID='a61cbf9c',
                       APIKey='8bf44c5bf73cac72ad1df3710d828c40',
                       APISecret='NzkzYzg2MGE1YWI5ZjhkNjAxZDIwZjBl',
                       Text=svc)
    websocket.enableTrace(False)
    wsUrl = wsParam.create_url()
    ws = websocket.WebSocketApp(wsUrl, on_message=on_message, on_error=on_error, on_close=on_close,on_open=on_open)
    ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE})


    pygame.mixer.init()  # 开始播放MP3
    track = pygame.mixer.music.load('demo.mp3')
    pygame.mixer.music.play()
    time.sleep(10)
    pygame.mixer.music.stop()